package com.itheima.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户管理接口")
@RequestMapping("/users")
@RestController
@RequiredArgsConstructor
@Slf4j
public class userController {
    // 通过构造函数的方式注入
    private final UserService userService;

    @ApiOperation("新增用户")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO userFormDTO) {
        log.info("新增用户：{}", userFormDTO);
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        userService.save(user);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public void deleteUserById(@PathVariable("id") Long id) {
        log.info("删除用户：{}", id);
        userService.removeById(id);
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("/{id}")
    public UserVO getUserById(@PathVariable("id") Long id) {
        log.info("根据id查询用户: {}", id);
        User user = userService.getById(id);
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    @ApiOperation("根据id批量查询")
    @GetMapping
    public List<UserVO> listUserByIds(@RequestParam("ids")List<Long> ids){
        log.info("根据id批量查询: {}", ids);
        List<User> userList = userService.listByIds(ids);
        return BeanUtil.copyToList(userList, UserVO.class);
    }

    @ApiOperation("根据id扣余额")
    @PutMapping("/{id}/deduction/{money}")
    public void deductBalanceById(@PathVariable("id") Long id, @PathVariable("money") Integer money){
        log.info("根据id扣余额：{}, {}", id, money);
        userService.deleteBalanceById(id, money);
    }

    @GetMapping("/list")
    public List<UserVO> QueryUsers(UserQuery userQuery){
        return userService.QueryUsers(userQuery);
    }
}
